package online.hxstart.code.concurrent.chapter12;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

  private static final int port = 8080;

  public static void main(String[] args) {
    System.out.println("Server...\n");
    Server server = new Server();
    server.init();
  }

  private void init() {
    try {
      ServerSocket serverSocket = new ServerSocket(port);
      while (true) {
        Socket client = serverSocket.accept();
        System.out.println(client);
        new HandlerThread(client);
      }
    } catch (Exception e) {
      System.out.println("服务器异常: " + e.getMessage());
    }
  }

  private class HandlerThread implements Runnable {

    private Socket socket;

    public HandlerThread(Socket client) {
      socket = client;
      new Thread(this).start();
    }

    @Override
    public void run() {
      try {
        //创建一个流套接字并将其连接到指定主机上的指定端口号
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream out = new PrintStream(socket.getOutputStream());
        while (true) {
          try {

            String ret = input.readLine();
            System.out.println("客户端端返回过来的是: " + ret);
            // 如接收到 "OK" 则断开连接
            if ("OK".equals(ret)) {
              System.out.println("客户端将关闭连接");
              Thread.sleep(500);
              input.close();
              break;
            }
            //读取服务器端数据
            //向服务器端发送数据
            out.println(ret);
          } catch (Exception e) {
            System.out.println("客户端异常:" + e.getMessage());
            throw e;
          }
        }
        out.close();
        input.close();
      } catch (Exception e) {
        System.out.println("服务器 run 异常: " + e.getMessage());
      } finally {
        if (socket != null) {
          try {
            socket.close();
          } catch (Exception e) {
            socket = null;
            System.out.println("服务端 finally 异常:" + e.getMessage());
          }
        }
      }
    }
  }
}
